import { Node, instantiate, Label, UITransform, tween, Layout, v3, UIOpacity } from "cc";
import { ToastTipsProxy } from "../../script/proxy/ToastTipsProxy";
import { bind } from "../../core/module/proxy/ProxyDecorator";
import { UIBase } from "../../core/module/ui/UIBase";

@bind(ToastTipsProxy)
export class ToastTips extends UIBase<ToastTipsProxy> {
    readonly fadeTime: number = 1;
    readonly startPos: number = 0;
    readonly space: number = 20;
    readonly delayTime: number = 2;


    private _tips: Node[] = [];

    onInit(): void {
        this._view.item.active = false
    }

    onShow(): void {
        super.onShow()
        this._showTips(this.args)
    }

    /**
     * 显示提示
     * @param msg 
     */
    private _showTips(msg: string) {
        const ins = instantiate(this._view.item);
        ins.setParent(this._view.node)
        ins.active = true
        this._tips.unshift(ins);

        const label = ins.getComponentInChildren(Label)
        label.string = msg
        label.updateRenderData(true)
        ins.getComponent(Layout).updateLayout(true)

        let totalLength = 0;
        for (let i = 0; i < this._tips.length; i++) {
            let item = this._tips[i];
            let height = item.getComponent(UITransform).height
            if (i == 0) {
                item.setPosition(v3(item.position.x, this.startPos))
                totalLength += height / 2
            }
            else {
                item.setPosition(v3(item.position.x, this.startPos + totalLength + height / 2))
                totalLength += height
            }
            totalLength += this.space;
        }
        let uiOpacity = ins.getComponent(UIOpacity)
        tween(uiOpacity)
            .delay(this.delayTime)
            .to(this.fadeTime, { opacity: 0 }, { easing: 'backOut' })
            .call(() => {
                this._tips.splice(this._tips.indexOf(ins), 1);
                ins.destroy()
            })
            .start()
    }

}